package com.usernet.product.web.action;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.usernet.product.comm.BaseAction;
import com.usernet.product.comm.HibernateSessionFactory;
import com.usernet.product.entity.Admin;
import com.usernet.product.entity.Photo;
import com.usernet.product.entity.Resources;
import com.usernet.product.entity.Software;
import com.usernet.product.entity.Type;
import com.usernet.product.tools.APK;
import com.usernet.product.tools.APKTools;
import com.usernet.product.tools.FileTools;
import com.usernet.product.utils.DateUtils;
import com.usernet.product.utils.LogConstants;
import com.usernet.product.utils.Page;
import com.usernet.product.utils.PageResult;
import com.usernet.product.utils.ProductConfig;
import com.usernet.product.utils.ProductUtils;
import com.usernet.product.utils.StringUtils;
import com.usernet.product.web.form.SoftwareForm;

public class SoftwareAction extends BaseAction {

	public ActionForward toList(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		SoftwareForm mForm = (SoftwareForm) form;
		// 查询条件
		String softName = mForm.getSoftName();
		int typeId = mForm.getTypeIds();
		int resId = mForm.getResIds();
		int isTops = mForm.getIsTops();
		int isMoney = mForm.getIsMoney();
		int isUsed = mForm.getIsUsed();

		PageResult<Software> result = null;
		Page page = new Page();
		// 分页信息
		String pageNo = mForm.getPageNo();
		String pageSize = mForm.getPageSize();
		if (pageSize != null) {
			page.setEveryPage(Integer.parseInt(pageSize.trim()));
		}
		if (pageNo != null) {
			page.setCurrentPage(Integer.parseInt(pageNo.trim()));
		}
		// 条件查询
		if (softName != null || typeId != -1 || isTops != -1 || isMoney != -1
				&& isUsed != -1 && resId != -1) {
			// 有条件
			result = softwareDao.getAllByParams(page, softName, typeId, isTops,
					isMoney, isUsed, resId);
		} else {
			result = softwareDao.getAllByPage(page);
		}

		List<Type> typeList = typeDao.getAll();
		List<Resources> resourcesList = resourcesDao.getAll();
		request.setAttribute("resourcesList", resourcesList);

		request.setAttribute("form", mForm);
		request.setAttribute("typeList", typeList);
		request.setAttribute("list", result.getContent());
		request.setAttribute("page", result.getPage());
		request.setAttribute("size", result.getSize());

		return mapping.findForward("list");
	}

	public ActionForward toAdd1(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		return mapping.findForward("add1");
	}

	// 上传解析apk
	public ActionForward doAdd1(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws FileNotFoundException, IOException {
		SoftwareForm mForm = (SoftwareForm) form;
		FormFile file = mForm.getIcon();
		if (file != null && file.getFileSize() > 0) {
			String name = file.getFileName();
			String fileType = name.substring(name.lastIndexOf("."), name
					.length());
			if (!".apk".equals(fileType.toLowerCase())) {
				request.setAttribute("msg", "应用类型错误,必须为APK");
				request.setAttribute("return", "software.do?method=toList");
				return mapping.findForward("admin_msg");
			} else {
				String realPath = ProductConfig.realPath;
				InputStream in = file.getInputStream();

				String fileName = StringUtils.getUUID()
						+ name.substring(name.lastIndexOf("."), name.length());
				String filePath = realPath + "upload\\software\\"
						+ DateUtils.getDate() + "\\";
				String apkPath = filePath + fileName;
				// 创建文件夹
				FileTools.createDateFile(filePath);
				try {
					OutputStream out = new FileOutputStream(apkPath);
					int fileSize = file.getFileSize();
					String size = "";
					// 计算文件大小
					if (fileSize < 1024 * 1024) {
						size = (fileSize / 1024) + "KB";
					} else {
						size = new DecimalFormat(".##")
								.format((double) fileSize / (1024 * 1024))
								+ "MB";
					}
					out.write(file.getFileData(), 0, fileSize);
					in.close();
					in = null;
					out.close();
					out = null;
					APK apk = APKTools.getAPK(apkPath);
					apk.setDownload(DateUtils.getDate() + "/" + fileName);
					byte[] byteArr = APKTools.getIcon(apkPath, apk
							.getIconPath());

					String icon = null;
					if (byteArr != null) {
						icon = StringUtils.getUUID();
						String fileIconPath = realPath + "upload\\icon\\"
								+ DateUtils.getDate() + "\\";
						String iconPath = fileIconPath + icon;
						// 创建文件夹
						FileTools.createDateFile(fileIconPath);
						out = new FileOutputStream(iconPath);
						out.write(byteArr);
						out.flush();
						out.close();
						out = null;
					}
					apk.setSize(size); // 文件大小
					apk.setIcon(DateUtils.getDate() + "/" + icon);
					List<Type> types = typeDao.getAll();
					request.setAttribute("types", types);
					List<Resources> resourcesList = resourcesDao.getAll();
					request.setAttribute("resourcesList", resourcesList);
					request.setAttribute("apk", apk); // 传递apk安装包信息
				} catch (Exception ex) {
					ex.printStackTrace();
					File oldFile = new File(apkPath);
					if (oldFile.exists()) {
						oldFile.delete();
					}
				}
			}
		}

		return mapping.findForward("add2");
	}

	// 添加应用信息
	public ActionForward doAdd2(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		String name = request.getParameter("name");
		String version = request.getParameter("version");
		String code = request.getParameter("code");
		String sdk = request.getParameter("sdk");
		String icon = request.getParameter("iconName");
		int recommend = ProductConfig.DEFAULT_RECOMMEND; // 默认推荐顺序都为100000
		int tops = Integer.parseInt(request.getParameter("tops"));// 不推荐和不顶置：0推荐：1；顶置：2
		Timestamp time = new Timestamp(System.currentTimeMillis());
		String size = request.getParameter("size");
		String develope = request.getParameter("develope");
		String remark = request.getParameter("remark");
		int avg = Integer.parseInt(request.getParameter("avg"));
		int share = Integer.parseInt(request.getParameter("share"));
		String m = request.getParameter("money");
		double money = 0.0;
		if (!"".equals(m)) {
			money = Double.parseDouble(m);
		}
		int count = ProductConfig.DEFAULT_DOWN_COUNT; // 默认下载次数0
		int typeId = Integer.parseInt(request.getParameter("typeId"));
		String download = request.getParameter("download");
		String pinyin = ProductUtils.getFullChars(name);
		String tag = request.getParameter("tag");
		int recId = Integer.parseInt(request.getParameter("recId"));
		String res = request.getParameter("res");
		String package_ = request.getParameter("package_");
		int status = ProductConfig.DEFAULT_AVG; // 默认状态可用
		Admin admin = (Admin) request.getSession().getAttribute("admin");
		String username = admin.getLoginName();

		Software soft = new Software();
		soft.setName(name);
		soft.setVersion(version);
		soft.setCode(code);
		soft.setSdk(sdk);
		soft.setIcon(icon);
		soft.setRecommend(recommend);
		soft.setTops(tops);
		soft.setTime(time);
		soft.setSize(size);
		soft.setDevelope(develope);
		soft.setRemark(remark);
		soft.setAvg(avg);
		soft.setShare(share);
		soft.setMoney(money);
		soft.setCount(count);
		Type type = new Type();
		type.setId(typeId);
		soft.setType(type);
		soft.setDownload(download);
		soft.setPinyin(pinyin);
		soft.setTag(tag);
		if (recId != 0) {
			Resources rec = new Resources();
			rec.setId(recId);
			soft.setResources(rec);
		}
		soft.setRes(res);
		soft.setPackage_(package_);
		soft.setStatus(status);
		soft.setUsername(username);

		int id = softwareDao.save(soft);
		if (id > 0) {
			// 添加日志
			ProductUtils.addAdminLog(request, admin.getLoginName(), String
					.format(LogConstants.add_software, new Object[] { id,
							soft.getName() }), null);
			request.setAttribute("id", id);
			return mapping.findForward("add3");
		} else {
			request.setAttribute("msg", "添加失败");
			request.setAttribute("return", "software.do?method=toList");
			return mapping.findForward("admin_msg");
		}
	}

	public ActionForward toAdd3(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws FileNotFoundException, IOException {
		request.setAttribute("id", request.getParameter("id"));
		return mapping.findForward("add3");
	}

	// 添加截图信息
	public ActionForward doAdd3(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws FileNotFoundException, IOException {
		int softId = Integer.parseInt(request.getParameter("id"));
		Hashtable<?, ?> files = form.getMultipartRequestHandler()
				.getFileElements();
		int count = 0;
		if (files != null & files.size() > 0) {
			Enumeration<?> enums = files.keys();
			String fileKey = null;
			int i = 0;
			String filePath = ProductConfig.realPath + "upload\\photo\\"
					+ DateUtils.getDate() + "\\";
			FileTools.createDateFile(filePath);
			while (enums.hasMoreElements()) {
				// 取得key
				fileKey = (String) (enums.nextElement());
				// 初始化每一个FormFile(接口)
				FormFile file = (FormFile) files.get(fileKey);
				// 分别上传
				String name = file.getFileName();
				if (name != null && !"".equals(name.trim())) {
					String fileType = name.substring(name.lastIndexOf("."),
							name.length());
					if (!".png".equals(fileType.toLowerCase())
							&& !".jpg".equals(fileType.toLowerCase())) {
						request.setAttribute("msg", "已经添加成功了" + count
								+ "张,图片类型错误,必须为PNG或JPG");
						request.setAttribute("return",
								"/admin/page/software_add_3.jsp&id=" + softId);
						return mapping.findForward("admin_msg");
					} else {
						String photpName = StringUtils.getUUID();

						InputStream in = file.getInputStream();

						OutputStream out = new FileOutputStream(filePath
								+ photpName);
						out.write(file.getFileData(), 0, file.getFileSize());
						in.close();
						in = null;
						out.close();
						out = null;
						Photo photo = new Photo();
						photo.setPhoto(DateUtils.getDate() + "/" + photpName);
						photo.setStatus(0);// 可用
						Software soft = new Software();
						soft.setId(softId);
						photo.setSoftware(soft);
						photo
								.setTime(new Timestamp(System
										.currentTimeMillis()));
						int photoId = photoDao.save(photo);
						if (photoId > 0) {
							count++;
						} else {
							request.setAttribute("msg", "添加失败,(已经添加成功了" + count
									+ "张)");
							request.setAttribute("return",
									"software.do?method=toList");
							return mapping.findForward("admin_msg");
						}
					}
				}
				i++;
			}

		}
		Admin admin = (Admin) request.getSession().getAttribute("admin");
		// 添加日志
		ProductUtils.addAdminLog(request, admin.getLoginName(), String.format(
				LogConstants.add_photo, new Object[] { files.size() }), null);
		return mapping.findForward("other");
	}

	/*
	 * 删除软件
	 */
	public ActionForward doDelete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		int id = Integer.parseInt(request.getParameter("id"));
		Software software = (Software) softwareDao.getById(Software.class, id);
		Session session = HibernateSessionFactory.getSession();
		Transaction tr = null;
		try {
			File file = new File(ProductConfig.realPath + "/upload/software/"
					+ software.getDownload());
			File file2 = new File(ProductConfig.realPath + "/upload/icon/"
					+ software.getIcon());
			tr = session.beginTransaction();
			Query query = session
					.createQuery("delete Comment photo where photo.software.id="
							+ id);
			query.executeUpdate();
			query = session
					.createQuery("delete Photo photo where photo.software.id="
							+ id);
			query.executeUpdate();
			query = session
					.createQuery("delete Error photo where photo.software.id="
							+ id);
			query.executeUpdate();

			query = session.createQuery("delete Software where id=" + id);
			query.executeUpdate();
			tr.commit();
			if (file.isFile() && file.exists()) {
				file.delete();
			}
			if (file2.isFile() && file2.exists()) {
				file2.delete();
			}
			Admin admin = (Admin) request.getSession().getAttribute("admin");
			// 添加日志
			ProductUtils.addAdminLog(request, admin.getLoginName(), String
					.format(LogConstants.delete_software, new Object[] { id,
							software.getName() }), null);
			return mapping.findForward("other");
		} catch (HibernateException e) {
			if (tr != null) {
				tr.rollback();
			}
			e.printStackTrace();
			request.setAttribute("msg", "删除失败," + e.getMessage());
			request.setAttribute("return", "software.do?method=toList");
			return mapping.findForward("admin_msg");
		}
	}

	/*
	 * 修改推荐顺序
	 */
	public ActionForward doSort(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		int sort = Integer.parseInt(request.getParameter("sort"));
		Software software = (Software) softwareDao.getById(Software.class, id);
		software.setRecommend(sort);
		if (softwareDao.modify(software)) {
			Admin admin = (Admin) request.getSession().getAttribute("admin");
			// 添加日志
			ProductUtils.addAdminLog(request, admin.getLoginName(), String
					.format(LogConstants.upadte_software_sort, new Object[] {
							sort, id, software.getName() }), null);
			response.getWriter().write("1");
			response.getWriter().flush();
		} else {
			response.getWriter().write("0");
			response.getWriter().flush();
		}
		return null;
	}

	/*
	 * 修改顶置
	 */
	public ActionForward doTops(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		int tops = Integer.parseInt(request.getParameter("tops"));
		Software software = (Software) softwareDao.getById(Software.class, id);
		software.setTops(tops);
		if (softwareDao.modify(software)) {
			Admin admin = (Admin) request.getSession().getAttribute("admin");
			// 添加日志
			if (tops == 2) {
				// 添加日志
				ProductUtils.addAdminLog(request, admin.getLoginName(), String
						.format(LogConstants.upadte_software_tops,
								new Object[] { id, software.getName() }), null);
			}
			if (tops == 1) {
				// 添加日志
				ProductUtils.addAdminLog(request, admin.getLoginName(), String
						.format(LogConstants.upadte_software_goods,
								new Object[] { id, software.getName() }), null);
			}
			response.getWriter().write("1");
			response.getWriter().flush();
		} else {
			response.getWriter().write("0");
			response.getWriter().flush();
		}
		return null;
	}

	/*
	 * 锁定
	 */
	public ActionForward doCancle(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		int id = Integer.parseInt(request.getParameter("id"));
		Software software = (Software) softwareDao.getById(Software.class, id);
		software.setStatus(1);// 不可用
		if (softwareDao.modify(software)) {
			Admin admin = (Admin) request.getSession().getAttribute("admin");
			// 添加日志
			ProductUtils.addAdminLog(request, admin.getLoginName(), String
					.format(LogConstants.lock_software, new Object[] { id,
							software.getName() }), null);
		}
		return mapping.findForward("other");
	}

	/*
	 * 解锁
	 */
	public ActionForward doOk(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		int id = Integer.parseInt(request.getParameter("id"));
		Software software = (Software) softwareDao.getById(Software.class, id);
		software.setStatus(0);// 可用
		if (softwareDao.modify(software)) {
			Admin admin = (Admin) request.getSession().getAttribute("admin");
			// 添加日志
			ProductUtils.addAdminLog(request, admin.getLoginName(), String
					.format(LogConstants.unlock_software, new Object[] { id,
							software.getName() }), null);
		}
		return mapping.findForward("other");
	}

	@SuppressWarnings("unchecked")
	public ActionForward toPhoto(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		int id = Integer.parseInt(request.getParameter("id"));
		List<Photo> photos = softwareDao
				.getAllByHql("from Photo where software.id=" + id);

		request.setAttribute("id", id);
		request.setAttribute("photos", photos);
		return mapping.findForward("photo");
	}

	/*
	 * to修改
	 */
	public ActionForward toUpdate(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		int id = Integer.parseInt(request.getParameter("id"));
		Software software = (Software) softwareDao.getById(Software.class, id);
		List<Type> types = typeDao.getAll();
		List<Resources> resourcesList = resourcesDao.getAll();

		request.setAttribute("types", types);
		request.setAttribute("resourcesList", resourcesList);
		request.setAttribute("software", software);
		return mapping.findForward("update");
	}

	/*
	 * do修改
	 */
	public ActionForward doUpdate(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		int id = Integer.parseInt(request.getParameter("id"));
		Software software = (Software) softwareDao.getById(Software.class, id);

		Admin admin = (Admin) request.getSession().getAttribute("admin");

		String name = request.getParameter("name");
		String sdk = request.getParameter("sdk");
		String develope = request.getParameter("develope");
		String remark = request.getParameter("remark");
		String share = request.getParameter("share");
		String m = request.getParameter("money");
		String typeId = request.getParameter("typeId");
		String tag = request.getParameter("tag");
		String recId = request.getParameter("recId");
		String res = request.getParameter("res");

		double money = 0.0;
		if (!"".equals(m)) {
			money = Double.parseDouble(m);
		}

		String pinyin = ProductUtils.getFullChars(name);
		software.setName(name);
		software.setSdk(sdk);
		software.setDevelope(develope);
		software.setRemark(remark);
		software.setShare(Integer.parseInt(share));
		software.setMoney(money);
		Type type = new Type();
		type.setId(Integer.parseInt(typeId));
		software.setType(type);
		software.setPinyin(pinyin);
		software.setTag(tag);
		int rid = Integer.parseInt(recId);
		if (rid != 0) {
			Resources rec = new Resources();
			rec.setId(rid);
			software.setResources(rec);
		} else {
			software.setResources(null);
		}
		software.setRes(res);
		software.setTime(new Timestamp(System.currentTimeMillis()));// 更新时间

		// 顶置推荐信息
		int tops = Integer.parseInt(request.getParameter("tops"));
		String recommend = request.getParameter("recommend");
		if (!"".equals(recommend)) {
			int recom = Integer.parseInt(recommend);
			if (recom != software.getRecommend()) {
				// 添加日志
				ProductUtils
						.addAdminLog(request, admin.getLoginName(), String
								.format(LogConstants.upadte_software_sort,
										new Object[] { recom, id,
												software.getName() }), null);
			}
			software.setRecommend(recom);
		}
		if (tops == 2) {
			// 添加日志
			ProductUtils.addAdminLog(request, admin.getLoginName(), String
					.format(LogConstants.upadte_software_tops, new Object[] {
							id, software.getName() }), null);
		}
		if (tops == 1) {
			// 添加日志
			ProductUtils.addAdminLog(request, admin.getLoginName(), String
					.format(LogConstants.upadte_software_goods, new Object[] {
							id, software.getName() }), null);
		}
		software.setTops(tops);
		// 评分信息
		int avg = Integer.parseInt(request.getParameter("avg"));
		if (avg != software.getAvg()) {
			// 添加日志
			ProductUtils.addAdminLog(request, admin.getLoginName(), String
					.format(LogConstants.upadte_software_avg, new Object[] {
							avg, id, software.getName() }), null);
		}
		software.setAvg(avg);

		if (softwareDao.modify(software)) {
			// 添加日志
			ProductUtils.addAdminLog(request, admin.getLoginName(), String
					.format(LogConstants.update_software, new Object[] { id,
							software.getName() }), null);
			return mapping.findForward("other");
		} else {
			request.setAttribute("msg", "修改失败");
			request.setAttribute("return", "software.do?method=toList");
			return mapping.findForward("admin_msg");
		}
	}

	/** to重新上传APK */
	public ActionForward toAPK(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		int id = Integer.parseInt(request.getParameter("id"));
		request.setAttribute("id", id);
		return mapping.findForward("apk");
	}

	/** to重新上传ICON */
	public ActionForward toICON(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		int id = Integer.parseInt(request.getParameter("id"));
		request.setAttribute("id", id);
		return mapping.findForward("icon");
	}

	/** 重新上传APK */
	public ActionForward doAPK(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws FileNotFoundException, IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		Software software = (Software) softwareDao.getById(Software.class, id);
		String oldApkPath = software.getDownload();
		String oldIconPath = software.getIcon();
		SoftwareForm mForm = (SoftwareForm) form;
		FormFile file = mForm.getIcon();
		if (file != null && file.getFileSize() > 0) {
			String name = file.getFileName();
			String fileType = name.substring(name.lastIndexOf("."), name
					.length());
			if (!".apk".equals(fileType.toLowerCase())) {
				request.setAttribute("msg", "应用类型错误,必须为APK");
				request.setAttribute("return", "software.do?method=toList");
				return mapping.findForward("admin_msg");
			} else {
				String realPath = ProductConfig.realPath;
				InputStream in = file.getInputStream();

				String fileName = StringUtils.getUUID()
						+ name.substring(name.lastIndexOf("."), name.length());
				String filePath = realPath + "upload\\software\\"
						+ DateUtils.getDate() + "\\";
				String apkPath = filePath + fileName;
				// 创建文件夹
				FileTools.createDateFile(filePath);
				try {
					OutputStream out = new FileOutputStream(apkPath);
					int fileSize = file.getFileSize();
					String size = "";
					// 计算文件大小
					if (fileSize < 1024 * 1024) {
						size = (fileSize / 1024) + "KB";
					} else {
						size = new DecimalFormat(".##")
								.format((double) fileSize / (1024 * 1024))
								+ "MB";
					}
					out.write(file.getFileData(), 0, fileSize);
					in.close();
					in = null;
					out.close();
					out = null;
					APK apk = APKTools.getAPK(apkPath);
					apk.setDownload(DateUtils.getDate() + "/" + fileName);
					byte[] byteArr = APKTools.getIcon(apkPath, apk
							.getIconPath());

					String icon = null;
					if (byteArr != null) {
						icon = StringUtils.getUUID();
						String fileIconPath = realPath + "upload\\icon\\"
								+ DateUtils.getDate() + "\\";
						String iconPath = fileIconPath + icon;
						// 创建文件夹
						FileTools.createDateFile(fileIconPath);
						out = new FileOutputStream(iconPath);
						out.write(byteArr);
						out.flush();
						out.close();
						out = null;
					}
					// 以下为要修改的信息
					software.setSize(size); // 文件大小
					software.setIcon(DateUtils.getDate() + "/" + icon);
					software.setDownload(apk.getDownload());
					software.setPackage_(apk.getPackageName());
					software.setCode(apk.getVersionCode());
					software.setVersion(apk.getVersionName());
					software.setSdk(apk.getSdkVersion());
					software.setTime(new Timestamp(System.currentTimeMillis()));

					if (softwareDao.modify(software)) {
						File oldApk = new File(ProductConfig.realPath
								+ "upload\\software\\" + oldApkPath);
						if (oldApk.exists()) {
							oldApk.delete();
						}
						File oldIcon = new File(ProductConfig.realPath
								+ "upload\\icon\\" + oldIconPath);
						if (oldIcon.exists()) {
							oldIcon.delete();
						}
						Admin admin = (Admin) request.getSession()
								.getAttribute("admin");
						// 添加日志
						ProductUtils
								.addAdminLog(
										request,
										admin.getLoginName(),
										String
												.format(
														LogConstants.upload_software_apk,
														new Object[] {
																id,
																software
																		.getName() }),
										null);
						return mapping.findForward("other");
					}
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		}

		request.setAttribute("msg", "重新上传APK失败");
		request.setAttribute("return", "software.do?method=toList");
		return mapping.findForward("admin_msg");
	}

	/** 重新上传ICON */
	public ActionForward doICON(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws FileNotFoundException, IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		Software software = (Software) softwareDao.getById(Software.class, id);
		String oldIconPath = software.getIcon();
		SoftwareForm mForm = (SoftwareForm) form;
		FormFile file = mForm.getIcon();
		if (file != null && file.getFileSize() > 0) {
			String name = file.getFileName();
			String fileType = name.substring(name.lastIndexOf("."), name
					.length());
			if (!".png".equals(fileType.toLowerCase())
					&& !".jpg".equals(fileType.toLowerCase())) {
				request.setAttribute("msg", "应用类型错误,必须为png或jpg");
				request.setAttribute("return", "software.do?method=toList");
				return mapping.findForward("admin_msg");
			} else {
				try {
					String realPath = ProductConfig.realPath + "upload\\icon\\"
							+ DateUtils.getDate() + "\\";
					// 创建文件
					FileTools.createDateFile(realPath);
					InputStream in = file.getInputStream();
					String fileName = StringUtils.getUUID();
					OutputStream out = new FileOutputStream(realPath + fileName);
					out.write(file.getFileData(), 0, file.getFileSize());
					in.close();
					in = null;
					out.close();
					out = null;

					// 一下为要修改的信息
					software.setIcon(DateUtils.getDate() + "/" + fileName);
					software.setTime(new Timestamp(System.currentTimeMillis()));

					if (softwareDao.modify(software)) {
						File oldIcon = new File(ProductConfig.realPath
								+ "upload\\icon\\" + oldIconPath);
						if (oldIcon.exists()) {
							oldIcon.delete();
						}
						Admin admin = (Admin) request.getSession()
								.getAttribute("admin");
						// 添加日志
						ProductUtils
								.addAdminLog(
										request,
										admin.getLoginName(),
										String
												.format(
														LogConstants.upload_software_icon,
														new Object[] {
																id,
																software
																		.getName() }),
										null);
						return mapping.findForward("other");
					}
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		}
		request.setAttribute("msg", "重新上传ICON失败");
		request.setAttribute("return", "software.do?method=toList");
		return mapping.findForward("admin_msg");
	}
}
